const _ = require('lodash')
const crypto = require('crypto')

exports.throwError = function (status) {
  let msg = ''
  if (this.errors) msg = _.values(this.errors[0])[0]
  this.throw(msg, status)
}

/**
 * 返回错误响应体
 * @param msg 错误信息字符串，如果是字符串数组，则取第一条
 * @param code 错误代码，可为空
 * @returns {Object}
 */
exports.apiError = function (msg, code) {
  return {
    success: false,
    msg: msg || 'Unknown error',
    code: code
  }
}

/**
 * 返回正确响应体
 * @param data 数据对象，若是字符串，则赋值到msg上
 * @param code 错误代码，可为空
 * @returns {Object}
 */
exports.apiSuccess = function (data) {
  let obj = { success: true }
  if (typeof data === 'string') obj.msg = data
  else if (typeof data === 'object') obj = _.assign(obj, data)
  return obj
}

/**
 * 生成mongodb连接字符串
 * @param config 配置对象
 * @returns {String}
 */
exports.createConnStr = function (config) {
  let hosts = config.hosts instanceof Array
      ? config.hosts.join(',') : config.hosts
  let auth = config.username && config.password
      ? `${config.username}:${config.password}@` : ''
  let options = config.option instanceof Array
      ? config.option.join('&') : config.option ? config.option : ''
  return `mongodb://${auth}${hosts}/${config.name}?${options}`
}

/**
 * md5加密
 * @param str
 * @returns {String}
 */
exports.md5 = function (str) {
  return crypto.createHash('md5').update(str).digest('hex')
}

/**
 * 获取token字符串
 */
exports.getJwtToken = function (ctx) {
  let authorization = ctx.header.authorization
  if (authorization) {
    let arr = authorization.split(' ')
    if (arr[1]) return arr[1]
  }
  return ''
}
